const _ = require('lodash');
const emq = require('mqtt');

module.exports = class {
    constructor(app) {
        this.app = app;
        this.config = app.config;
        this.client = undefined;
        app.eventBus.on("HTTP_DATA_RECEVED", (data) => {
            const {topic, payload} = data;
            console.log(" mqtt publish", topic)
            this.publish(topic, payload);

        })
    }

    async connect(ip, port) {
        const qos = 0;
        const opts = {port, qos};
        const url = ip + ":" + port;
        this.client = emq.connect(url, opts);
        this.client.on('connect', packet => {
            console.log("connect ok ", ip, port)
            this.client.on('error', error => {
                console.log(error, url);
                this.app.logger.error('IIOT平台连接 error', url);
                this.app.eventBus.emit('MQTT_CONNECTED', 'error');
            });
            this.client.on('close', error => {
                this.app.logger.error('IIOT平台连接 close', url);
                this.app.eventBus.emit('MQTT_CONNECTED', 'close');
            });

            this.client.on('offline', error => {
                this.app.logger.error('IIOT平台连接 offline', url);
                this.app.eventBus.emit('MQTT_CONNECTED', 'offline');
            });
            return Promise.resolve('');
        });
    }

    publish(topic, payload) {

        if (this.client && this.client.connected) {
            const opt = {qos: 0, retain: false};
            if (typeof payload === 'object') {
                payload = JSON.stringify(payload);
            }

            this.client.publish(topic, payload, opt, err => {
                if (err) {
                    this.app.logger.error('mqtt pub error', topic, err);
                }
            });


        } else {
            this.app.logger.error('mqtt router isnot connected', topic, payload);
        }
    }
}
